//
//  TeamProfile.m
//  playSerengetiMobile1
//
//  Created by Lita Gratrix on 12/11/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "UserProfile.h"
#import "TeamProfile.h"
#import "JSON/JSON.h"

#define kViewTag	1		//for tagging embedded controls for removal at cell recycle time

#define ROW_HEIGHT_FOR_TABLE	30

static NSString *kSectionTitleKey = @"sectionTitleKey";
static NSString *kSourceKey = @"sourceKey";
static NSString *kViewKey = @"viewKey";

@implementation TeamProfile

@synthesize teamId;
@synthesize teamNameLabel, homeBaseLabel, teamLeaderLabel, teamProfileTableView;
@synthesize profile, members;
@synthesize tableSourceArray;
@synthesize appDelegate;

- (void)viewDidLoad{
	[super viewDidLoad];
	
//	NSLog(@"Entering TeamProfile viewDidLoad\n");
//	NSLog(@"TeamProfile.teamId is %d\n", teamId);
	
	self.appDelegate = (playSerengetiMobile1AppDelegate *)[[UIApplication sharedApplication] delegate];
	
	responseDataForTeamProfileConnection = [[NSMutableData data] retain];
	responseDataForTeamLeaderConnection = [[NSMutableData data] retain];
	NSString *URLString = [NSString stringWithFormat:@"%@team/%d/json", appDelegate.baseURL, teamId];
//	NSLog(@"SubmitString for teamProfile is %@\n", URLString);
	NSURLRequest *teamProfileRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];
	teamProfileConnection = [[NSURLConnection alloc] initWithRequest:teamProfileRequest delegate:self];
	
	self.profile = [[Team alloc] init];
	self.members = [[NSMutableArray alloc] init];
	self.tableSourceArray = [NSArray arrayWithObjects:
							 [NSDictionary dictionaryWithObjectsAndKeys:
							 @"Members", kSectionTitleKey,
							  self.members, kSourceKey, nil], nil];
}


- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

#pragma mark -
#pragma mark Populate View Data Methods

- (void)populateViewData:(NSDictionary *)parsedData{
	profile.teamId = [[parsedData objectForKey:@"id"] integerValue];
	profile.teamName = [parsedData objectForKey:@"name"];
	profile.color = [parsedData objectForKey:@"color"];
	profile.description = [parsedData objectForKey:@"description"];
	profile.homeBase = [parsedData objectForKey:@"homeBase"];
	
	teamNameLabel.text = profile.teamName;
	homeBaseLabel.text = profile.homeBase;
	
	NSInteger teamLeaderId = [[parsedData objectForKey:@"leaderId"] integerValue];
	NSMutableArray *memberArray = [parsedData objectForKey:@"members"];
	
	[self getTeamLeaderData:teamLeaderId];
	[self populateMembers:memberArray];
	
	[self.teamProfileTableView reloadData];
	
}

- (void)getTeamLeaderData: (NSInteger)teamLeaderId {
	NSString *URLString = [NSString stringWithFormat:@"%@user/%d/json", appDelegate.baseURL, teamLeaderId];
//	NSLog(@"SubmitString for teamProfile is %@\n", URLString);
	NSURLRequest *teamLeaderRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];
	teamLeaderConnection = [[NSURLConnection alloc] initWithRequest:teamLeaderRequest delegate:self];	
}

- (void)populateTeamLeader:(NSDictionary *)parsedData{
//	NSLog(@"Entering populateTeamLeader\n");
	User *teamLeader = [[User alloc] init];
	NSDictionary *userDic = [parsedData objectForKey:@"user"];
	teamLeader.userId = [[userDic objectForKey:@"id"] integerValue];
	teamLeader.name = [userDic objectForKey:@"name"];
	teamLeader.email = [userDic objectForKey:@"email"];
	profile.leader = teamLeader;
//	NSLog(@"teamLeader.email is %@",profile.leader.email);
	if(profile.leader.email != nil){
		teamLeaderLabel.text = profile.leader.name;
	}else{
		teamLeaderLabel.text = @"No team owner yet!";
	}
}

- (void)populateMembers:(NSMutableArray *)memberArray {
//	NSLog(@"Entering populate Member array\n");
	if([memberArray count] == 0){
		//Do something
	}else {
		[members removeAllObjects];
		int i;
		for (i = 0; i < [memberArray count]; i++){
			User *user = [[User alloc] init];
//			NSLog(@"memberArray object at %d is %@", i, [memberArray objectAtIndex:i]);
			NSDictionary *memberDic = [memberArray objectAtIndex:i];
			user.userId = [[memberDic objectForKey:@"id"] integerValue];
			user.name = [memberDic objectForKey:@"name"];
			user.email = [memberDic objectForKey:@"email"];
//			NSLog(@"Adding user %d, %@ to members.\n", user.userId, user.email);
			[members addObject:user];
		}
	}
}

#pragma mark -
#pragma mark NSURLConnectionDelegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	if(connection == teamProfileConnection){
		[responseDataForTeamProfileConnection setLength:0];
	}else if (connection == teamLeaderConnection) {
		[responseDataForTeamLeaderConnection setLength:0];
	}
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	if(connection == teamProfileConnection){
		[responseDataForTeamProfileConnection appendData:data];
	}else if (connection == teamLeaderConnection) {
		[responseDataForTeamLeaderConnection appendData:data];
	}
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	if(connection = teamProfileConnection){
		teamNameLabel.text = [NSString stringWithFormat:@"teamNameConnection failed: %@\n", [error description]];
	}else if (connection = teamLeaderConnection){
		teamNameLabel.text = [NSString stringWithFormat:@"teamLeaderConnection failed: %@\n", [error description]];
	}
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	if(connection == teamProfileConnection){
		[connection release];
	
//		NSLog(@"Succeeded! Received %d bytes of data\n",[responseDataForTeamProfileConnection length]); 
		NSString *responseString = [[NSString alloc] initWithData:responseDataForTeamProfileConnection encoding:NSUTF8StringEncoding];
//		NSLog(@"responseString for teamProfileConnection reads: %@\n", responseString);
	
		[responseDataForTeamProfileConnection release];
	
		NSDictionary *parsedData = [responseString JSONValue];
	
		[responseString release];

		if (parsedData == nil) {
			teamNameLabel.text = [NSString stringWithFormat:@"Error in returned data.\n"];
		} else {
			[self populateViewData:(NSDictionary *)parsedData];
		}
	}else if(connection == teamLeaderConnection){
		[connection release];
		
//		NSLog(@"Succeeded! Received %d bytes of data\n",[responseDataForTeamLeaderConnection length]);  
		NSString *responseString = [[NSString alloc] initWithData:responseDataForTeamLeaderConnection encoding:NSUTF8StringEncoding];
//		NSLog(@"responseString for teamLeaderConnection reads: %@\n", responseString);		
		
		[responseDataForTeamLeaderConnection release];
		
		NSDictionary *parsedData = [responseString JSONValue];
		
		[responseString release];		
		
		if(parsedData == nil) {
			teamNameLabel.text = [NSString stringWithFormat:@"Error in returned data.\n"];
		} else {
			[self populateTeamLeader:parsedData];
		}
	}
}	

#pragma mark -
#pragma mark UITableViewDataSourceDelegate Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return [tableSourceArray count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	return [[self.tableSourceArray objectAtIndex: section] valueForKey:kSectionTitleKey];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	//	NSLog(@"Entering tableView:%@ numberOfRowsInSection:%d", tableView, section);
	NSMutableArray *sectionData = [[self.tableSourceArray objectAtIndex:section] valueForKey:kSourceKey];
	//	NSLog(@"number of expected rows: %d.\n", [sectionData count]);
	return [sectionData count];
}

// to determine specific row height for each cell, override this.
// In this example, each row is determined by its subviews that are embedded.
//
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return ROW_HEIGHT_FOR_TABLE;
	//return ([indexPath row] == 0) ? 50.0 : 38.0;
}

// to determine which UITableViewCell to be used on a given row.
//
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell *cell = nil;
	User *aUser;
	
	aUser = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
	
	static NSString *kDisplayCell_ID = @"DisplayCellID";
	cell = [self.teamProfileTableView dequeueReusableCellWithIdentifier:kDisplayCell_ID];
	if (cell == nil)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kDisplayCell_ID] autorelease];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
	}
	else
	{
		// the cell is being recycled, remove old embedded controls
		UIView *viewToRemove = nil;
		viewToRemove = [cell.contentView viewWithTag:kViewTag];
		if (viewToRemove){
			[viewToRemove removeFromSuperview];
		}
	}
	
	UIControl *control = [[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kViewKey];
	[cell.contentView addSubview:control];
	
	cell.textLabel.text = aUser.name;
	
//	[aUser release];
//	aUser = nil;
	
	return cell;
}

#pragma mark -
#pragma mark UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	User *aUser;
	aUser = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
	UserProfile *aUserProfileView = [[UserProfile alloc] initWithNibName:@"UserProfile" bundle:nil];
	aUserProfileView.userId = aUser.userId;
//	[aUser release];
//	aUser = nil;
	[self.view addSubview:aUserProfileView.view];	
}


@end
